package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private  BlogMapper blogMapper;
    @Resource
    private IFollowService followService;


    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            //判断点过赞没，图标是否高亮显示
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 查看博客
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        //1.查询博客
        Blog blog = getById(id);
        if(blog == null) {
            return  Result.fail("该博客已被删除了");
        }
        //2.查询blog相关的用户
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        //判断点过赞没，图标是否高亮显示
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if(user == null) {
            //用户为登录，无需查询点赞
            return;
        }
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + blog.getId(), UserHolder.getUser().getId().toString());
        blog.setIsLike(score != null);
    }
    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    /**
     * 点赞
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        Long userId = UserHolder.getUser().getId();
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + id, userId.toString());
        //没点过赞
        if(score == null) {
            update().setSql("liked = liked + 1").eq("id", id).update();
            stringRedisTemplate.opsForZSet().add(RedisConstants.BLOG_LIKED_KEY+id, userId.toString(),System.currentTimeMillis());
        } else {
            //点过赞了
            update().setSql("liked = liked - 1").eq("id", id).update();
            stringRedisTemplate.opsForZSet().remove(RedisConstants.BLOG_LIKED_KEY+id,userId.toString());
        }
        return Result.ok();
    }

    /**
     * 点赞排行榜
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        //查询TOP5个点赞的用户
        Set<String> range = stringRedisTemplate.opsForZSet().range(RedisConstants.BLOG_LIKED_KEY + id, 0, 4);
        if(range == null || range.isEmpty()) {
            return  Result.ok(Collections.emptyList());
        }
        //解析出id
        List<Long> ids = range.stream().map(Long::valueOf).collect(Collectors.toList());
        List<User> users = blogMapper.queryTOP5(ids);
        //根据id查询用户
        List<UserDTO> userDTOList = users.stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOList);
    }

    /**
     * 发布博客
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 2.保存探店博文
        boolean save = save(blog);
        if(!save){
            return Result.fail("发布博客笔记失败惹");
        }
        //sql:select * from tb_follow where follow_user_id = {userid}
        // 3.得到粉丝ids
        List<Long> follow_user_id = followService.query().eq("follow_user_id", user.getId())
                .list()
                .stream()
                .map(follow_user -> follow_user.getUserId()).collect(Collectors.toList());
        //4.推送博客笔记id给所有粉丝
        follow_user_id.forEach(ids-> {
            String key=RedisConstants.FEED_KEY+ids;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(), System.currentTimeMillis());
        });
        // 5.返回id
        return Result.ok(blog.getId());
    }

    /**
     * 收件箱的笔记滚动分页
     * @param max
     * @param offset
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2.查看收件箱 ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count]
        // 根据score 从高向低开始查询（max,min是范围）， offset：符合范围的第几个开始查，0的话就是小于等于max的第一个就开始，count：查询几个
        String key=RedisConstants.FEED_KEY+userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 3);
        if(typedTuples == null || typedTuples.isEmpty()) {
            return  Result.ok();
        }
        // 3.把信息解析一下，博客id，score(时间戳)，offset
        //我们要拿到一个数据，就是最小分数有几个重复的 5 5   5   5
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long MinScore = 0;
        int count = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //获取id
            String value = typedTuple.getValue();
            ids.add(Long.valueOf(value));
            //获取score
            long score = typedTuple.getScore().longValue();
            if(score == MinScore) {
                count++;
            } else {
                MinScore = score;
                count = 1;
            }
        }
        // 4.根据博客id查询博客
        List<Blog> blogs = blogMapper.queryBlogByIds(ids);
        for (Blog blog : blogs) {
            //4.1博客关联的用户
            queryBlogUser(blog);
            //4.2博客是否点赞了
            isBlogLiked(blog);
        }
        // 5.封装返回
        ScrollResult scrollResult=new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setMinTime(MinScore);
        scrollResult.setOffset(count);
        return  Result.ok(scrollResult);
    }

}
